package com.caiyigo.struts.daoImpl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.caiyigo.struts.dao.IDepartmentDao;
import com.caiyigo.struts.dao.IEmployeeDao;
import com.caiyigo.struts.model.Department;
import com.caiyigo.struts.model.Employee;

public class EmployeeDaoImpl implements IEmployeeDao {
	private static Map<Integer, Department> departmentsMap;
	private static ArrayList<Employee> employees;
	static {
		employees = new ArrayList<Employee>();
		employees.add(new Employee(new Integer(1), "小明", "王", new Integer(36),
				new Department(new Integer(100), "研发部"), "50000"));
		employees.add(new Employee(new Integer(2), "三丰", "张", new Integer(25),
				new Department(new Integer(300), "销售部"), "35000"));
		IDepartmentDao deptDao = new DepartmentDaoImpl();
		departmentsMap = deptDao.getDepartmentsMap();
	}

	public List<Employee> getAllEmployees() {
		return employees;
	}

	public Employee getEmployeeById(Integer id) {
		Employee emp = null;
		Iterator<Employee> iter = employees.iterator();
		while (iter.hasNext()) {
			emp = (Employee) iter.next();
			if (emp.getEmployeeId().equals(id)) {
				break;
			}
		}
		return emp;
	}

	public void update(Employee employee) {
		Integer id = employee.getEmployeeId();
		for (int i = 0; i < employees.size(); i++) {
			Employee tempEmp = (Employee) employees.get(i);
			if (tempEmp.getEmployeeId().equals(id)) {
				employee.setDepartment((Department) departmentsMap.get(employee
						.getDepartment().getDepartmentId()));
				employees.set(i, employee);
				break;
			}
		}
	}

	public void insert(Employee employee) {
		int lastId = 0;
		Iterator<Employee> iter = employees.iterator();
		while (iter.hasNext()) {
			Employee temp = (Employee) iter.next();
			if (temp.getEmployeeId().intValue() > lastId) {
				lastId = temp.getEmployeeId().intValue();
			}
		}
		employee.setDepartment((Department) departmentsMap.get(employee
				.getDepartment().getDepartmentId()));
		employee.setEmployeeId(new Integer(lastId + 1));
		employees.add(employee);
	}

	public void deleteById(Integer id) {
		for (int i = 0; i < employees.size(); i++) {
			Employee tempEmp = (Employee) employees.get(i);
			if (tempEmp.getEmployeeId().equals(id)) {
				employees.remove(i);
				break;
			}
		}
	}
}